using System.Collections.Generic;
using System.Threading;
using Microsoft.Xna.Framework;
using RebEngine.Interfaces;
using RebEngine.Models;

namespace RebEngine.Managers
{
    public class ModelManager : GameComponent
    {
        private static List<string> sentInstructions = new List<string>();
        private static Dictionary<string, RebModel> _models = new Dictionary<string, RebModel>();
        private static bool _initialized = false;
        private static int _modelsLoaded = 0;

        public static int ModelsLoaded
        {
            get { return _modelsLoaded; }
        }
        public static bool Initialized
        {
            get { return _initialized; }
        }

        public ModelManager(Game game)
            : base(game)
        {
            AddModel("cube");
        }

        public static void AddModel(string modelName)
        {
            RebModel newModel = new RebModel(modelName);
            if (modelName != null && !_models.ContainsKey(modelName))
            {
                _models.Add(modelName, newModel);
                if (_initialized)
                {
                    newModel.LoadContent();
                    _modelsLoaded++;
                }
            }
        }

        public static RebModel GetModel(string modelName)
        {
            if (modelName != null && _models.ContainsKey(modelName))
            {
                return _models[modelName];
            }
            else
            {
                string message = "ModelManager: Missing Model Content named " + modelName + ". Loading default";
                if (!sentInstructions.Contains(message))
                {
                    sentInstructions.Add(message);
                    LogManager.Write(message);
                }
                return _models["cube"];
            }
        }

        public override void Initialize()
        {
            base.Initialize();

            foreach (IRebModel model in _models.Values)
            {
                if (!model.ReadyToRender)
                {
                    model.LoadContent();
                    _modelsLoaded++;
                }
            }
            _initialized = true;
        }
    }
}
